package homework8_5;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBUtil {

	// public class Contants {
	// public static final String url =
	// "jdbc:mysql://localhost:3306/java61?useSSL=false";// 数据库地址
	// // ?useSSL=false不使用加密模式
	// public static final String user = "root";// 数据库用户名
	// public static final String password = "123456";// 数据库密码
	// }
	static String url;
	static String user;
	static String password;
	static String driver;
	static {
		// final String driver = "com.mysql.jdbc.Driver";// mysql驱动
		Properties p = new Properties();
		try {
			p.load(DBUtil.class.getClassLoader().getResourceAsStream("homework8_5/subject.properties"));
			driver = p.getProperty("driver");
			url = p.getProperty("url");
			user = p.getProperty("user");
			password = p.getProperty("password");
			Class.forName(driver);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}

	private DBUtil() {
	}

	public static Connection getConnection() {
		Connection con = null;
		try {
			// Class.forName(driver);
			con = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return con;

	}

	public static void close(ResultSet rs, Statement s, Connection con) {
		close(rs);
		close(s);
		close(con);
	}

	public static void close(Connection con) {
		if (con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(Statement stm) {
		if (stm != null) {
			try {
				stm.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	// 通用的CUD操作
	/**
	 * 
	 * @param sql语句
	 * @param 参数
	 * @return 影响的行数
	 */
	public static int executeUpdate(String sql, Object... args) {

		Connection con = DBUtil.getConnection();
		PreparedStatement ps = null;
		try {
			ps = con.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}

			return ps.executeUpdate();
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
			close(ps);
			close(con);
		}

		return 0;
	}

}
